<?php

namespace app\admin\service;

use app\common\Error;
use app\model\DistributorsSharingStatistics;
// use think\facade\Session;
use app\model\DistributionSettlement;
use app\model\ResponsibilityPerson;
use app\model\Link;
use app\model\Videos;
use app\model\PayRecord;
use think\facade\Db;
use app\model\Company;
use app\model\DistributorsH5SmsSharingStatistics;

class DistributionService
{
    private $distributorsSharingStatisticsModel;
    private $distributionSettlementModel;
    private $responsibilityPersonModel;
    private $linkModel;
    private $videosModel;
    private $payRecordModel;
    private $companyModel;
    private $distributorsH5SmsSharingStatisticsModel;

    public function __construct(DistributorsSharingStatistics $distributorsSharingStatisticsModel,DistributorsH5SmsSharingStatistics $distributorsH5SmsSharingStatisticsModel, DistributionSettlement $distributionSettlementModel, ResponsibilityPerson $responsibilityPersonModel, Link $linkModel, Videos $videosModel, PayRecord $payRecordModel, Company $companyModel)
    {
        $this->distributorsSharingStatisticsModel = $distributorsSharingStatisticsModel;
        $this->distributionSettlementModel = $distributionSettlementModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->linkModel = $linkModel;
        $this->videosModel = $videosModel;
        $this->payRecordModel = $payRecordModel;
        $this->companyModel = $companyModel;
        $this->distributorsH5SmsSharingStatisticsModel = $distributorsH5SmsSharingStatisticsModel;
    }

    // 获取分销商分成列表
    public function getDividedStatisticsList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        // 日期搜索
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        // 分销商搜索
        if (!empty($params['distributor_id'])) {
            $where[] = ['distributor_id', '=', $params['distributor_id']];
        }

        $data = $this->distributorsSharingStatisticsModel->getPagingDataByWhere($where, $page, $limit, 'date, name, company_name, recharge_price, refund_price, commission, scale, sharing_amount, ly_sharing_amount,virtual_recharge_price,virtual_refund_price,virtual_commission,common_commission,virtual_scale,common_recharge_price,common_refund_price,common_scale,ad_incentive_amount,virtual_amount,common_amount');

        if ($data['data']) {
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['date'] = substr($value['date'], 0, 4).'-'.substr($value['date'], 4, 2).'-'.substr($value['date'], 6, 2);
            }
        }

        return $data;
    }

    // 分成合计
    public function getDivideIntoTotal($params)
    {
        $where = [];
        // 日期搜索
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        // 分销商搜索
        if (!empty($params['distributor_id'])) {
            $where[] = ['distributor_id', '=', $params['distributor_id']];
        }

        $data['recharge_price'] = $this->distributorsSharingStatisticsModel->getCount($where, 'recharge_price');

        $data['commission'] = $this->distributorsSharingStatisticsModel->getCount($where, 'commission');

        $data['refund_price'] = $this->distributorsSharingStatisticsModel->getCount($where, 'refund_price');

        $data['sharing_amount'] = $this->distributorsSharingStatisticsModel->getCount($where, 'sharing_amount');

        $data['ly_sharing_amount'] = $this->distributorsSharingStatisticsModel->getCount($where, 'ly_sharing_amount');

        $data['virtual_recharge_price'] = $this->distributorsSharingStatisticsModel->getCount($where, 'virtual_recharge_price');

        $data['virtual_refund_price'] = $this->distributorsSharingStatisticsModel->getCount($where, 'virtual_refund_price');

        $data['common_recharge_price'] = $this->distributorsSharingStatisticsModel->getCount($where, 'common_recharge_price');

        $data['common_refund_price'] = $this->distributorsSharingStatisticsModel->getCount($where, 'common_refund_price');

        $data['ad_incentive_amount'] = $this->distributorsSharingStatisticsModel->getCount($where, 'ad_incentive_amount');

        $data['virtual_amount'] = $this->distributorsSharingStatisticsModel->getCount($where, 'virtual_amount');

        $data['common_amount'] = $this->distributorsSharingStatisticsModel->getCount($where, 'common_amount');

        $data['common_commission'] = $this->distributorsSharingStatisticsModel->getCount($where, 'common_commission');

        $data['virtual_commission'] = $this->distributorsSharingStatisticsModel->getCount($where, 'virtual_commission');

        return $data;
    }

    // 分销商下拉列表
    public function getSelectList()
    {
        $data = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id, name');
        return $data;
    }

    // 分销商今日充值
    public function getRealTimeRechargeList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;

        $where = [];
        // 分销商搜索
        if (!empty($params['distributor_id'])) {
            $where[] = ['pid', '=', $params['distributor_id']];
        } else {
            $distributorData = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id');
            $distributorResponsibilityPersonIds = array_column($distributorData, 'id');
            $where[] = ['pid', 'in', $distributorResponsibilityPersonIds];
        }

        // 获取分销商数据
        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere($where, 'id, name');
        $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');

        $distributorsData = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id, name');
        $distributors = array_column($distributorsData, 'name', 'id');

        $linkWhere = [];
        // 搜索短剧
        if (!empty($params['video_id'])) {
            $linkWhere[] = ['video_id', '=', $params['video_id']];
        }

        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $linkWhere[] = ['link_type', '=', $params['link_type']];
        }

        // 投放媒体搜索
        if (!empty($params['media_id'])) {
            $linkWhere[] = ['media_id', '=', $params['media_id']];
        }
        $linkWhere[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        $linkWhere[] = ['recharge_price', '>', 0];

        // 充值金额排序
        if (!empty($params['recharge_price_sort'])) {
            $order = 'recharge_price '.$params['recharge_price_sort'];
        } else {
            $order = 'id desc';
        }
        // 链接数据
        $data = $this->linkModel->getPagingDataByWhere($linkWhere, $page, $limit, 'id, video_id, link_switch, media_id, echo_rate, recharge_price, responsibility_person_id', $order);

        if ($data['data']) {
            $linkIds = array_column($data['data'], 'id');
            $videoIds = array_column($data['data'], 'video_id');
            $responsibilityPerson = array_column($data['data'], 'responsibility_person_id');
            $responsibilityPersonInfo = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPerson], 'id, pid');
            $personInfo = array_column($responsibilityPersonInfo, 'pid', 'id');

            // 短剧数据
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $video = array_column($videoData, 'name', 'id');

            // 充值数据
            $payWhere = [
                ['status', '=', 1],
                ['pay_time', '>=', strtotime(date('Y-m-d'))],
                ['pay_time', '<=', strtotime(date('Y-m-d').' 23:59:59')],
                ['link_id', 'in', $linkIds]
            ];
            $rechargeData = $this->payRecordModel->getInfo($payWhere, 'link_id, total_fee, uid, activation_date');
            $recharge = [];
            foreach ($rechargeData as $key => $value) {
                $recharge[$value['link_id']][] = $value;
            }

            // 组装数据
            foreach ($data['data'] as $key => $value) {
                $rechargePrice = 0; // 充值金额
                $rechargePeopleNumber = 0; // 充值人数
                $newRechargePeopleNumber = 0; // 新充值人数
                $newRechargeNumber = 0; // 新充笔数
                $perCapita = 0; // 人均

                $rechargeUid = $newRechargeUid = [];
                if (!empty($recharge[$value['id']])) {
                    foreach ($recharge[$value['id']] as $item) {
                        $rechargePrice += $item['total_fee'];
                        $rechargeUid[] = $item['uid'];
                        if ($item['activation_date'] == date('Ymd')) {
                            $newRechargeNumber += 1;
                            $newRechargeUid[] = $item['uid'];
                        }
                    }
                }

                $data['data'][$key]['today_recharge_price'] = round($rechargePrice, 2); // 今日充值金额
                $data['data'][$key]['recharge_people_number'] = $rechargePeopleNumber =  empty($rechargeUid) ? 0 : count(array_unique($rechargeUid)); // 充值人数
                $data['data'][$key]['new_recharge_people_number'] = empty($newRechargeUid) ? 0 : count(array_unique($newRechargeUid));
                $data['data'][$key]['new_recharge_number'] = $newRechargeNumber;
                $data['data'][$key]['per_capita'] = empty($rechargePeopleNumber) ? '0' : round($rechargePrice / $rechargePeopleNumber, 2);

                $data['data'][$key]['video_name'] = empty($video[$value['video_id']]) ? '' : $video[$value['video_id']];

                $personPId = empty($personInfo[$value['responsibility_person_id']]) ? '' : $personInfo[$value['responsibility_person_id']];
                $data['data'][$key]['distributor_name'] = empty($personPId) || empty($distributors[$personPId]) ? '' : $distributors[$personPId];
            }
        }
        return $data;
    }

    // 分销商充值排名
    public function getRealTimeRechargeRankingList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $offset = ($page - 1) * $limit;
        $where = [];
        // 日期搜索
        if (!empty($params['start_date'])) {
            $time = $params['start_date'];
            $where[] = ['o.pay_time', '>=', strtotime($params['start_date'])];
        } else {
            $time = date('Y-m-d');
            $where[] = ['o.pay_time', '>=', strtotime("today")];
        }

        if (!empty($params['distributor_id'])) {
            $where[] = ['c1.id', '=', $params['distributor_id']];
        }

        if (!empty($params['end_date'])) {
            $time = $time.' 00:00:00 ~ '.$params['end_date'].' 23:59:59';
            $where[] = ['o.pay_time', '<', strtotime($params['end_date'].' 23:59:59')];
        }

        if (!empty($params['video_id'])) {
            $where[] = ['o.video_id', '=', $params['video_id']];
        }

        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $where[] = ['c3.link_type', '=', $params['link_type']];
        }

        $where[] = ['c1.is_distributor', '=', 1];

        $data = Db::table('ly_responsibility_person c1')
            ->field('c1.name, SUM(o.total_fee) as total_order_amount')
            ->join('ly_responsibility_person c2', 'c1.id = c2.pid ')
            ->join('ly_link c3', 'c2.id = c3.responsibility_person_id')
            ->join('ly_pay_record o', 'c3.id = o.link_id')
            ->where($where)
            ->group('c1.name')
            ->order('total_order_amount', 'DESC')
            ->select()
            ->toArray();
        /* $total   =   Db::table('ly_responsibility_person c1')->field('c1.name')
            ->join('ly_responsibility_person c2','c1.id = c2.pid ')
            ->join('ly_link c3','c2.id=c3.responsibility_person_id')
            ->join('ly_pay_record o','c3.id = o.link_id')->where($where)->group('c1.name')
            ->count();//总条数
        $count_total_fee   =   Db::table('ly_responsibility_person c1')->field('c1.name')
            ->join('ly_responsibility_person c2','c1.id = c2.pid ')
            ->join('ly_link c3','c2.id=c3.responsibility_person_id')
            ->join('ly_pay_record o','c3.id = o.link_id')->where($where)->group('c1.name')
            ->sum('total_fee');//总充值
        */
        foreach ($data as $k => $v) {
            $data[$k]['time'] = $time;
        }

        return $data;
    }

    // 分销商短剧统计列表
    public function getShortRealTimeRechargeRankingList($params)
    {
        $where = [];
        // 日期搜索
        if (empty($params['start_date']) && empty($params['end_date'])) {
            $date = date('Y-m-d');
            $startTime = strtotime($date);
            $where[] = ['o.pay_time', '>=', $startTime];

            $endTime = strtotime($date . ' 23:59:59');
            $where[] = ['o.pay_time', '<=', $endTime];
        }
        if (!empty($params['start_date'])) {
            $startTime = strtotime($params['start_date']);
            $where[] = ['o.pay_time', '>=', $startTime];
        }
        if (!empty($params['end_date'])) {
            $endTime = strtotime($params['end_date'] . ' 23:59:59');
            $where[] = ['o.pay_time', '<=', $endTime];
        }
        // 分销商公司搜索
        if (!empty($params['distributor_id'])) {
            $where[] = ['c3.id', '=', $params['distributor_id']];
        }
        // 剧名搜索
        if (!empty($params['video_id'])) {
            $where[] = ['c2.video_id', '=', $params['video_id']];
        }
        $where[] = ['o.status', '=', 1];
        $where[] = ['c3.is_distributor', '=', 1];

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $offset = ($page - 1) * $limit;

        // 排序
        if (!empty($params['total_recharge_sort'])) {
            $order = 'total_recharge '.$params['total_recharge_sort'];
        } else {
            $order = 'o.consume_date DESC';
        }

        $data = Db::table('ly_pay_record o')
                ->field('o.consume_date as date, c2.video_id, c3.company_id, SUM(o.total_fee) as total_recharge, sum(case when o.pay_merchant = 15 then o.total_fee end) as virtually_recharge')
                ->join('ly_link c2', 'c2.id = o.link_id')
                ->join('ly_responsibility_person c4', 'c4.id = c2.responsibility_person_id')
                ->join('ly_responsibility_person c3', 'c3.id = c4.pid')
                ->where($where)
                ->group('o.consume_date, c2.video_id, c4.company_id')
                ->order($order)
                ->limit($offset, $limit)
                ->select()
                ->toArray();

        $companyIds = array_column($data, 'company_id');
        $videoIds = array_column($data, 'video_id');
        // 
        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
        $video = array_column($videoData, 'name', 'id');
        $companyData = $this->companyModel->getDataByWhere(['id' => $companyIds], 'id, name');
        $company = array_column($companyData, 'name', 'id');
        foreach ($data as $key => $item) {
            $data[$key]['date'] = substr($item['date'], 0, 4) . '-' . substr($item['date'], 4, 2) . '-' . substr($item['date'], 6, 2);
            $data[$key]['video_name'] = empty($video[$item['video_id']]) ? '' : $video[$item['video_id']];
            $data[$key]['company_name'] = empty($company[$item['company_id']]) ? '' : $company[$item['company_id']];
            $data[$key]['virtually_recharge'] = empty($item['virtually_recharge']) ? 0 : round($item['virtually_recharge'], 2);
            $data[$key]['not_virtually_recharge'] = round($item['total_recharge'] - $item['virtually_recharge'], 2);
        }

        return $data;
    }

    // 分销商短剧统计总数
    public function getShortRealTimeRechargeRankingCount($params)
    {
        $where = [];
        // 日期搜索
        if (empty($params['start_date']) && empty($params['end_date'])) {
            $date = date('Y-m-d');
            $startTime = strtotime($date);
            $where[] = ['o.pay_time', '>=', $startTime];

            $endTime = strtotime($date . ' 23:59:59');
            $where[] = ['o.pay_time', '<=', $endTime];
        }
        if (!empty($params['start_date'])) {
            $startTime = strtotime($params['start_date']);
            $where[] = ['o.pay_time', '>=', $startTime];
        }
        if (!empty($params['end_date'])) {
            $endTime = strtotime($params['end_date'] . ' 23:59:59');
            $where[] = ['o.pay_time', '<=', $endTime];
        }
        // 分销商公司搜索
        if (!empty($params['distributor_id'])) {
            $where[] = ['c3.id', '=', $params['distributor_id']];
        }
        // 剧名搜索
        if (!empty($params['video_id'])) {
            $where[] = ['c2.video_id', '=', $params['video_id']];
        }
        $where[] = ['o.status', '=', 1];
        $where[] = ['c3.is_distributor', '=', 1];

        $data = Db::table('ly_pay_record o')
                ->field('SUM(o.total_fee) as total_recharge, sum(case when o.pay_merchant = 15 then o.total_fee end) as virtually_recharge')
                ->join('ly_link c2', 'c2.id = o.link_id')
                ->join('ly_responsibility_person c4', 'c4.id = c2.responsibility_person_id')
                ->join('ly_responsibility_person c3', 'c3.id = c4.pid')
                ->where($where)
                ->group('o.consume_date, c2.video_id, c4.company_id')
                ->select()
                ->toArray();
        $total = count($data);

        $countRecharge = $countVirtuallyRecharge = 0;
        foreach ($data as $key => $value) {
            $countRecharge += $value['total_recharge'];
            $countVirtuallyRecharge += $value['virtually_recharge'];
        }

        $limit = $params['limit'] ?? 20;
        $totalPage = ceil($total / $limit);

        return ['total' => $total, 'total_page' => $totalPage, 'count_recharge' => round($countRecharge, 2), 'count_virtually_recharge' => round($countVirtuallyRecharge, 2), 'count_not_virtually_recharge' => round($countRecharge - $countVirtuallyRecharge, 2)];
    }

    // 分销商今日累计充值
    public function getRealTimeRechargeSum($params)
    {
        $toDay = date('Ymd');
        $where = [
            'o.status' => 1,
            'o.consume_date' => $toDay,
            'c3.is_distributor' => 1,
        ];
        // 分销商搜索
        if (!empty($params['distributor_id'])) {
            $distributorWhere[] = ['pid', '=', $params['distributor_id']];
            $where['c3.id'] = $params['distributor_id'];
        } else {
            $distributorData = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id');
            $distributorResponsibilityPersonIds = array_column($distributorData, 'id');
            $distributorWhere[] = ['pid', 'in', $distributorResponsibilityPersonIds];
        }

        // 获取分销商数据
        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere($distributorWhere, 'id');
        $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');

        $linkWhere = [];
        // 搜索短剧
        if (!empty($params['video_id'])) {
            $linkWhere[] = ['video_id', '=', $params['video_id']];
            $where['c2.video_id'] = $params['video_id'];
        }
        // 投放媒体搜索
        if (!empty($params['media_id'])) {
            $linkWhere[] = ['media_id', '=', $params['media_id']];
            $where['c2.media_id'] = $params['media_id'];
        }
        $linkWhere[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];

        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $linkWhere[] = ['link_type', '=', $params['link_type']];
            $where['c2.link_type'] = $params['link_type'];
        }

        $data = Db::table('ly_pay_record o')
                ->field('o.total_fee, o.uid, o.link_id, o.activation_date')
                ->join('ly_link c2', 'c2.id = o.link_id')
                ->join('ly_responsibility_person c4', 'c4.id = c2.responsibility_person_id')
                ->join('ly_responsibility_person c3', 'c3.id = c4.pid')
                ->where($where)
                ->select()
                ->toArray();

        // 累计充值数据
        $linkIds = array_column($data, 'link_id');
        $linkWhere[] = ['id', 'in', $linkIds];
        $linkData = $this->linkModel->getDataByWhere($linkWhere, 'recharge_price');
        $totalRecharge = round(array_sum(array_column($linkData, 'recharge_price')), 2);

        $rechargePrice = array_sum( array_column($data, 'total_fee') );
        $peopleNumber = count( array_unique( array_column($data, 'uid') ) );
        $perCapita = empty($peopleNumber) ? 0 : round($rechargePrice / $peopleNumber, 2);

        $newPeopleNum = [];
        $newFrequency = 0;
        foreach ($data as $key => $value) {
            if ($value['activation_date'] == $toDay) {
                $newPeopleNum[] = $value['uid'];
                $newFrequency += 1;
            }
        }
        $newPeopleNumber = count(array_unique($newPeopleNum));

        $rechargePrice = round($rechargePrice, 2);
        $perCapita = round($perCapita, 2);
        return [
            'new_people_number' => $newPeopleNumber,
            'new_frequency' => $newFrequency,
            'total_recharge_price' => $rechargePrice,
            'total_per_capita' => $perCapita,
            'total_people_number' => $peopleNumber,
            'total_recharge' => $totalRecharge
        ];
    }

	// 分销商H5短信分成列表
    public function getSmsSharingList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        // 日期搜索
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        // 分销商搜索
        if (!empty($params['distributor_id'])) {
            $where[] = ['distributor_id', '=', $params['distributor_id']];
        }

        $data = $this->distributorsH5SmsSharingStatisticsModel->getPagingDataByWhere($where, $page, $limit, 'date,name,recharge_price,refund_price,commission,sharing_amount,ly_sharing_amount');

        if ($data['data']) {
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['date'] = substr($value['date'], 0, 4).'-'.substr($value['date'], 4, 2).'-'.substr($value['date'], 6, 2);
            }
        }

        return $data;
    }
}